import {getCurrentInstance} from 'vue'
const instance= getCurrentInstance()
const bus = instance?.appContext.config.globalProperties.$bus
const heartBeatInterval = 3000
const heartBeatMsg = 'ping'
let heartBearTimeout
class WebSocketClient{
    constructor(url){
        this.url = url ||'ws://www.sinobroad.com:54200/api/ws'
        this.connection = null;
        this.isConnected = false
    }
    connect(){
        if(this.isConnected){
            return
        }
        this.connection = new  WebSocket(this.url)
        this.connection.onopen = this.onOpen.bind(this)
        this.connection.onmessage = this.onMessage.bind(this)
        this.connection.onclose = this.onClose.bind(this)
    }
    onOpen(){
        this.isConnected = true
        console.error('WebSocket isConnected')
    }
    onMessage(e){
        bus.$emit('updatePoint',e.data)
    }
    onError(error){
        console.error('WebSocket:',error)
    }
    onClose(){
        this.isConnected = false
    }
    send(data){
        if(this.isConnected){
            this.connection.send(data)
        }else{
            console.error('WebSocket not connected')
        }
    }
    close(){
        if(this.isConnected) this.connection.close()
    }
}
let ws = new WebSocketClient()
ws.connect()
export default ws
export function socketInit(){
    const ws = new WebSocket('ws://www.sinobroad.com:41381/api/ws')
    ws.onopen = function(){
        console.log('connected')
        // startHeartbeat()
    }
    ws.onmessage = function(event){
        if(event.data){
    
        }
    }
    ws.onclose = function(){
        clearTimeout(heartBearTimeout)
    }
    function startHeartbeat(){
        ws.send(heartBeatMsg)
    
        heartBearTimeout = setTimeout(() => {
            ws.send(heartBeatMsg)
        }, heartBeatInterval);
    }
    
    function stopHeartbeat(){
        clearTimeout(heartBearTimeout)
    }

    return ws
}

